<?php
# Do not allow to run on live servers
if($_SERVER['SERVER_NAME']!='localhost')
{
	die('I cannot work on live server! Rather check my <a href="source.php">source code</a>.');
}

require_once('inc.config.php');
$mysql = array();

#$mysql_tables = mysql_list_tables($database); # Depricated
$mysql_tables = mysql_query("SHOW TABLES FROM {$database};");
#print_r($mysql_tables);

# Skip when no results
if(!mysql_num_rows($mysql_tables)) die('No tables');
while($mysql_table = mysql_fetch_row($mysql_tables))
{
	#print_r($mysql_table);
	$table = $mysql_table[0];

	# Skip list
	if(in_array($table, $skip_tables)) continue;
	
	$break = false;
	foreach($invalid_tables_regular_expressions as $itre => $invalid_table_regular_expression)
	{
		#die("{$invalid_table_regular_expression} - {$table}");
		#if(preg_match($invalid_table_regular_expression, $table)) continue;
		if(preg_match($invalid_table_regular_expression, $table))
		{
			$break = true;
			break;
		}
	}
	if($break) continue;
	
	# Wrapping with ticks (`) is important here in case the database contains table names that match with mysql keywords.
	$columns_result = mysql_query("SHOW COLUMNS FROM `{$table}`;") or die("Failed to read mysql columns on {$table} table.");
	if(mysql_num_rows($columns_result) > 0)
	{
		while($row = mysql_fetch_assoc($columns_result))
		{
			$column = $row['Field'];
			
			# skip list of columns
			if(in_array($column, $skip_columns)) continue;
			
			#print_r($row);
			$mysql[$mysql_table[0]][] = $column;
		}
	}
}
#print_r($mysql);

# Begin the matching process now.

# Try to match the columns in the database.
$matched = array();
foreach($mysql as $table => $columns)
{
	foreach($columns as $c => $column)
	{
		#echo "{$table}:{$column}\r\n"; # Nice lookup
		
		# Match the column with all other tables.
		# Skip the current table
		foreach($mysql as $target_table => $target_columns)
		{
			if($table == $target_table) continue;
			
			foreach($target_columns as $tc => $target_column)
			{
				if($column == $target_column)
				{
					# Yes, there is a match!
					
					# Check if matched already
					if(!empty($matched[$column]))
					{
						if(in_array($table, $matched[$column])) continue;
					}
					
					# The real/unique match is here
					$matched[$column][] = $table;
				}
			}
		}
	}
}

# Show full list of column names and tables containing it.
ksort($matched);
print_r($matched);

# List out all columns that were matched.
$columns = array_keys($matched);
sort($columns);
print_r($columns);
?>